import axios from 'axios';
import {ApiResult} from '@/phr/common/ApiResult';
import conf from '@/phrConf'
import {isNumber} from 'util';
import {ErrorCode} from '@/phr/common/ErrorCode';
import store from '@/store'

let axiosInstance = axios.create();
let baseUrl = conf.baseUrl;

class HttpClient {


    public async get<T=any>(url: string, params: object = null): Promise<ApiResult<T>> {
        url = baseUrl + url;
        if (params == null){
            params = {};
        }
        if (store.state.token != null){
            params['token'] = store.state.token;
        }
        return axiosInstance.get(url, {
            params: params
        }).then(res => {
            if (res.data.code != undefined && isNumber(res.data.code)) {
                res.data.code = ErrorCode.valueOf(res.data.code)
            }
            return res.data
        })
    }

    public async post<T = any>(url: string, params: object = {}): Promise<ApiResult<T>> {
        url = baseUrl + url;
        let formParam = new FormData();
        if (store.state.token != null){
            formParam.append("token",store.state.token);
        }
        for (let key in params) {
            if (params.hasOwnProperty(key)) {
                formParam.append(key, params[key])
            }
        }
        return axiosInstance.post(url, formParam).then(res => {
            if (res.data.code != undefined && isNumber(res.data.code)) {
                res.data.code = ErrorCode.valueOf(res.data.code)
            }
            return res.data
        })
    }

    // public setPhrToken(token:string){
    //     this.token = token;
    // }



}

const instance = new HttpClient();
export default instance;

